import React, {Key, useEffect, useState} from 'react';
import {Card, Row, Col, Tree, Tag, Pagination, Table, Button, message} from 'antd';
import type {
  hosScheduleListType,
  bookingScheduleListType,
  getScheduleWorkDateType,
} from '@api/hospital/model/hospitalListTypes';
import {
  hosScheduleListRequest,
  hosScheduleRuleRequest,
  getHosWorkDateScheduleRequest,
} from '@api/hospital/hospitalList';

import {useNavigate, useParams} from 'react-router-dom';


export default function HospitalSchedule() {
  const navigate = useNavigate();
  //创建控制排班列表参数
  const [treeData, setTreeData] = useState<hosScheduleListType>([]);
  //创建控制排班列表情况的参数
  const [bookingSchedule, setBookingSchedule] = useState<bookingScheduleListType>([]);
  //页码管理
  const [page, setPage] = useState(1);
  //每页条数管理
  const [limit, setLimit] = useState(3);
  //管理总数
  const [total, setTotal] = useState(0);
  //管理当日科室列表详情
  const [workDateList, setWorkDateList] = useState<getScheduleWorkDateType>([]);

  const [initDepcode,setInitDepcode] = useState('')
  const [startTime,setStartTime] = useState('')

  const {hoscode} = useParams();
  //1.获取科室列表数据
  const getScheduleList = async () => {
    const re = await hosScheduleListRequest(hoscode as string);
    // console.log('treeData', re)
    setTreeData(re);
    return re;
  };
  // 2.获取格式值班规则
  const getScheduleRule = async (
    depcode:string,
    page:number,
    limit:number
  ) => {
    const result = await hosScheduleRuleRequest({
      page,
      limit,
      hoscode: hoscode as string,
      depcode,
    });
    // console.log(bookingSchedule);
    setTotal(result.total);
    // console.log(resule);
    setBookingSchedule(result.bookingScheduleList);
    return result;
  };

  //3.获取排班详情
  const getFindScheduleList = async (workDate:string,depcode:string) => {
    const re = await getHosWorkDateScheduleRequest({
      hoscode: hoscode as string,
      depcode,
      workDate,
    });
    setWorkDateList(re);
  };
  //综合三个请求
  const getData = async () => {
    // 1.请求科室列表
    const getScheduleListResult = await getScheduleList();
    // console.log('result',getScheduleListResult);
    //  根据科室列表默认展示第一条数据
    //   console.log('no1',getScheduleListResult[0].depcode)
    const initDepcodeF = (getScheduleListResult[0].children as hosScheduleListType)[0].depcode
    setInitDepcode(initDepcodeF)
    const getScheduleRuleRe = await getScheduleRule(initDepcodeF,page,limit)
    //  更具排班的初始时间查找详细列表默认为第一个
    //   console.log('getScheduleRuleRe',getScheduleRuleRe);
    // console.log('初始时间',getScheduleRuleRe.bookingScheduleList[0].workDate);
    //保存初始时间
    const startTimeF = getScheduleRuleRe.bookingScheduleList[0].workDate
    // 发送请求 初始时间和默认对象的code
    await getFindScheduleList(startTimeF,initDepcode)
  };
  useEffect(() => {
    getData();
  }, []);


  const leftBox = {
    border: '1px solid #000',
    height: '400px',
    overflow: 'hidden',
  };

  //table结构
  const columns = [
    {
      title: '序号',
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: '职称',
      dataIndex: 'title',
    },
    {
      title: '号源时间',
      dataIndex: 'workDate',
    },
    {
      title: '可预约数',
      dataIndex: 'reservedNumber',
    },
    {
      title: '挂号费用',
      dataIndex: 'amount',
    },
    {
      title: '擅长技能',
      dataIndex: 'skill',
    },
  ];

  //1.回调函数集合管理
  //改变页码的事件回调函数
  const changePageHandle =async (page: number, limit: number) => {
    setPage(page);
    setLimit(limit);

    const scheduleRuleResult = await getScheduleRule(initDepcode,page,limit)
    const firstWorkDate = scheduleRuleResult.bookingScheduleList[0].workDate;
    getFindScheduleList(firstWorkDate,initDepcode)
  };
  //2.点击列表切换内容
  const changeDepartmentHandle = async (depcodeAll: Key[]) => {
    if (depcodeAll.length === 0){return}
    try {
      // console.log('depcode',depcode);
      setInitDepcode(depcodeAll[0] as string)
      const getScheduleRuleRe = await getScheduleRule(initDepcode,page,limit)
      setStartTime(getScheduleRuleRe.bookingScheduleList[0].workDate)
      // 发送请求 初始时间和默认对象的code
      await getFindScheduleList(startTime,initDepcode)
    }catch (e){
      message.error('没有查询到数据')
      setWorkDateList([])
    }

  };
  //3.
  const changeWorkDate = (workData:string) => {
    return () => {

      setStartTime(workData)
      console.log(workData);
      console.log(startTime);
    }
  };
  return (
    <Card>

      <Row gutter={20}>
        <Col span={5}>
          <div style={leftBox}>
            <Tree
              treeData={treeData as []}
              fieldNames={{
                title: 'depname',
                key: 'depcode',
                children: 'children',
              }}
              // expandedKeys = {["a4e171f4cf9b6816acdfb9ae62c414d7"]}
              height={400}
              onSelect={changeDepartmentHandle}
            />
          </div>
        </Col>
        <Col span={19}>
          <div style={{marginBottom: '20px'}}>
            {
              bookingSchedule.map((item, index) => {
                return (
                  <Tag
                    key={index}
                    onClick={changeWorkDate(item.workDate)}
                    style={{
                      cursor: 'pointer',
                      background: item.workDate === startTime ? "#1DA57A" : ""
                    }}
                  >
                    <div style={{marginTop: 5}}>
                      <span>{item.workDate}</span>
                      <span>{item.dayOfWeek}</span>
                    </div>
                    <p style={{textAlign: 'center', marginTop: 5}}>{item.availableNumber}/{item.reservedNumber}</p>
                  </Tag>
                );
              })
            }
          </div>
          <Pagination
            pageSize={limit}
            pageSizeOptions={[2, 4, 8, 12, 20]}
            showSizeChanger={true}
            total={total}
            onChange={changePageHandle}
          />
          <Table
            columns={columns}
            dataSource={workDateList}
            style={{marginTop: '20px'}}
            pagination={false}
            rowKey={'id'}
            bordered
          />
          <Button
            style={{marginTop: '10px'}}
            onClick={() => {
              navigate(-1);
            }}
          >返回</Button>
        </Col>
      </Row>

    </Card>
  );
}